package com.sky.d_thread;

import static org.junit.Assert.*;

import org.junit.Test;

public class InterruptTest {

	@Test
	public void testInterrupt1() throws Exception {
		
		Thread t = new Thread(){
			
			@Override
			public void run() {
				while(true){
					Thread.yield();
				}
			}
		};
		
		t.start();
		t.interrupt();
		
	}
	
	@Test
	public void testInterrupt2() throws Exception {
		
		Thread t = new Thread(){
			
			@Override
			public void run() {
				while(true){
					
					//这个很重要，当线程调用中断方法。只是打了个招呼，不会中止线程
					if(Thread.currentThread().isInterrupted()){
						System.out.println("Interrupt！");
						break;
					}
					Thread.yield();
				}
			}
		};
		
		t.start();
		t.interrupt();
	}
	
	@Test
	public void testInterrupt3() throws Exception {
		
		Thread t = new Thread(){
			
			@Override
			public void run() {
				while(true){
					if(Thread.currentThread().isInterrupted()){
						System.out.println("Interrupt！");
						break;
					}
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						System.out.println("Interrupted when sleep");
						//设置中断状态，抛出异常后会清除中断标记位
						Thread.currentThread().interrupt();
					}
					
					Thread.yield();
				}
			}
		};
		
		t.start();
		t.interrupt();
		
	}
}
